<?php
/*
 * @Descripttion: 
 * @Author: Twoknives
 * @Date: 2023-11-13 21:22:43
 * @LastEditTime: 2024-10-11 21:41:27
 * @FilePath: \xa-zhongcai-server\app\api\controller\User.php
 */

namespace app\api\controller;

use app\api\controller\Auth;
use app\api\model\SysLoginLog;
use app\api\model\Token;
use app\api\model\ApiUser as userModel;
use app\common\controller\ApiController;
use think\facade\Db;

class ApiUser extends ApiController
{

  protected $noNeedLogin = ['userLogin','userSsoLogin','thirdSsoLogin','thirdSsoLoginOut'];
  protected $mustLogin = [];

  public function thirdSsoLoginOut(){
    $param = $this->request->param();
    $saToken = $param['saToken'];
    $url = env('thirdSsoLogin.ssoApiUrl') . 'user/logout';
    $headers = [
        "saToken:".$saToken
    ];

    $context = stream_context_create([
        "http" => [
            "header" => implode("\r\n", $headers)
        ]
    ]);
    $response = file_get_contents($url, false, $context);
    $result = json_decode($response, true);
    if ($result['code'] == 200) {
      $this->success('退出登录成功');
    } else {
      $this->error('退出登录失败');
    }
  }

  //第三方单点登录
  public function thirdSsoLogin(){
    $param = $this->request->param();
    $saToken = $param['saToken'];
    //检查参数
    if (!isset($saToken)) {
      $this->error('saToken参数不能为空');
    }
    $result = $this->httpGet(env('thirdSsoLogin.ssoApiUrl') . 'user/getUserIdBySaToken', ['saToken' => $saToken, 'clientId' => env('thirdSsoLogin.clientId')]);
    if ($result['success']) {
        $data = json_decode($result['data'], true);
        
        if ($data['code'] == 200 ){
          if (isset($data['ssoId'])) {
              $this->success('登录成功', ['ssoId' => $data['ssoId']]);
          } else {
              $this->error('登录失败，ssoId不存在');
          }
        } else {
          $this->error($data['msg']);
        }
        $ssoId = $data['ssoId'];
        
    } else {
        $this->error('请求失败: ' . $result['error']);
    }
  }

  public function httpGet($url, $params = [], $headers = [], $timeout = 30) {
    // 构建完整URL
    if (!empty($params)) {
        $queryString = http_build_query($params);
        $url .= (strpos($url, '?') === false ? '?' : '&') . $queryString;
    } 
    $ch = curl_init();
    $defaultHeaders = [
        'User-Agent: PHP-HTTP-CLIENT/1.0',
        'Accept: */*'
    ];
    $allHeaders = array_merge($defaultHeaders, $headers);
    // var_dump($allHeaders);exit;
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_HTTPHEADER => $allHeaders
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    return [
        'success' => ($httpCode >= 200 && $httpCode < 300) && empty($error),
        'data' => $response,
        'http_code' => $httpCode,
        'error' => $error
    ];
}

  //获取专家列表
  public function getExpertList()
  {
    $param = $this->request->param();
    //检查参数
    if (!isset($param['type']) || !in_array($param['type'], [1, 2])) {
      $this->error('type参数错误');
    }
    $expertList = Db::name('sys_user')->where(['user_type' => $param['type'], 'delete_time' => NULL])->select();
    $this->success('获取成功', $expertList);
  }

  // 获取用户信息
  public function getUserInfo(){
    $user = Db::name('sys_user')->where(['user_id' => $this->uid, 'delete_time' => NULL])->field('user_name,user_type,avatar')->find(); 
    $this->success('获取成功', $user);
  }

  /**
   * 更新用户数据
   */
  public function updateUser(){
    $param = $this->request->param(); 
    //检查用户是否存在
    $user = Db::name('sys_user')->where(['user_id' => $this->uid])->find();
    if (!$user) {
      $this->error('用户不存在');
    }
    //更新用户数据
    $result = Db::name('sys_user')->where(['user_id' =>$this->uid])->update($param);
    if ($result) {
      $this->success('更新成功');
    } else {
      $this->error('更新失败');
    }
  }

  /**
   * 删除专家
   */
  public function deleteExpert()
  {
    $param = $this->request->param();

    //判断当前用户身份
    $currentUser = Db::name('sys_user')->where(['user_id' => $this->uid])->find();
    if ($currentUser['user_type'] != 1) {
      $this->error('没有权限');
    }

    //检查参数
    if (!isset($param['user_id'])) {
      $this->error('专家ID不能为空');
    }
    //检查专家是否存在
    $expert = Db::name('sys_user')->where(['user_id' => $param['user_id']])->find();
    if (!$expert) {
      $this->error('专家不存在');
    }
    //删除专家
    $result = Db::name('sys_user')->where(['user_id' => $param['user_id']])->update(['delete_time' => date('Y-m-d H:i:s')]);
    if ($result) {
      $this->success('删除成功');
    } else {
      $this->error('删除失败');
    }
  }

  //修改密码 旧密码 新密码
  public function changePassword()
  {
    $param = $this->request->param();
    //检查参数
    if (!isset($param['oldPassword']) || !isset($param['newPassword'])) {
      $this->error('旧密码或新密码不能为空');
    }
    //检查旧密码
    $user = Db::name('sys_user')->where(['user_id' => $this->uid])->find();
    if (!password_verify($param['oldPassword'], $user['password'])) {
      $this->error('旧密码错误');
    }
    //更新密码
    $result = Db::name('sys_user')->where(['user_id' => $this->uid])->update(['password' => password_hash($param['newPassword'], PASSWORD_DEFAULT)]);
    if ($result) {
      $this->success('修改成功');
    } else {
      $this->error('修改失败');
    }
  }

  //更新管理员
  public function updateAdmin(){
    $param = $this->request->param();
    //检查参数
    if (!isset($param['user_id'])) {
      $this->error('管理员ID不能为空');
    }
    //检查管理员是否存在
    $admin = Db::name('sys_user')->where(['user_id' => $param['user_id'],'delete_time' => NULL])->find();
    if (!$admin) {
      $this->error('管理员不存在');
    }
    //如果ssoId存在检查是否存在
    if (isset($param['ssoId']) && !empty($param['ssoId'])) {
      $user = Db::name('sys_user')->where(['ssoId' => $param['ssoId']])->where('user_id', '<>', $param['user_id'])->where(['delete_time' => NULL])->find();
      if ($user) {
        $this->error('SSO ID已存在');
      }
    }
    //如果密码存在，加密
    if (isset($param['password'])) {
      $param['password'] = password_hash($param['password'], PASSWORD_DEFAULT);
    } else {
      unset($param['password']);
    }
    //更新管理员
    $result = Db::name('sys_user')->where(['user_id' => $param['user_id'],'delete_time' => NULL])->update($param);
    if ($result) {
      $this->success('更新成功');
    } else {
      $this->error('更新失败');
    }
  }

  //更新专家
  public function updateExpert()
  {
    $param = $this->request->param();
    //检查参数
    if (!isset($param['user_id'])) {
      $this->error('专家ID不能为空');
    }
    //检查专家是否存在
    $expert = Db::name('sys_user')->where(['user_id' => $param['user_id'],'delete_time' => NULL])->find();
    if (!$expert) {
      $this->error('专家不存在');
    }
    //如果ssoId存在检查是否存在
    if (isset($param['ssoId']) && !empty($param['ssoId'])) {
      $user = Db::name('sys_user')->where(['ssoId' => $param['ssoId']])->where('user_id', '<>', $param['user_id'])->where(['delete_time' => NULL])->find();
      if ($user) {
        $this->error('SSO ID已存在');
      }
    }

    //如果密码存在，加密
    if (isset($param['password'])) {
      $param['password'] = password_hash($param['password'], PASSWORD_DEFAULT);
    } else {
      unset($param['password']);
    }
    //更新专家
    $result = Db::name('sys_user')->where(['user_id' => $param['user_id'],'delete_time' => NULL])->update($param);
    if ($result) {
      $this->success('更新成功');
    } else {
      $this->error('更新失败');
    }
  }

  //添加账号
  public function createAccount()
  {
    $param = $this->request->param();
    //判断当前用户身份
    $currentUser = Db::name('sys_user')->where(['user_id' => $this->uid])->find();
    if ($currentUser['user_type'] != 1) {
      $this->error('没有权限');
    }

    //如果ssoId存在检查是否存在
    if (isset($param['ssoId'])) {
      $user = Db::name('sys_user')->where(['ssoId' => $param['ssoId']])->where(['delete_time' => NULL])->find();
      if ($user) {
        $this->error('SSO ID已存在');
      }
    }

    //检查参数
    if (!isset($param['user_name']) || !isset($param['password'])) {
      $this->error('账号或密码不能为空');
    }
    //检查账号是否存在
    $user = Db::name('sys_user')->where(['user_name' => $param['user_name']])->where(['delete_time' => NULL])->find();
    if ($user) {
      $this->error('账号已存在');
    }
    //检查type参数
    if (!isset($param['type']) || !in_array($param['type'], [1, 2])) {
      $this->error('type参数错误');
    }
    //创建账号
    $param['password'] = password_hash($param['password'], PASSWORD_DEFAULT);
    $param['create_time'] = date('Y-m-d H:i:s');
    $param['update_time'] = date('Y-m-d H:i:s');
    $param['user_type'] = $param['type'];
    unset($param['type']);
    $param['delete_time'] = NULL;
    $result = Db::name('sys_user')->insert($param);
    if ($result) {
      $this->success('添加成功');
    } else {
      $this->error('添加失败');
    }
    //返回账号信息
    $this->success('添加成功', $param);
  }

  public function userSsoLogin()
  {
    $param = $this->request->param();
    //检查参数
    if (!isset($param['ssoId']) ) {
      $this->error('SSO ID不能为空');
    }
    $param['ssoId'] = $param['ssoId'];//base64_decode($param['ssoId']);//解密ssoId
    //查账号是否存在
    $loginRes = Db::name('sys_user')->where(['ssoId' => $param['ssoId'], 'delete_time' => NULL])->find();
    if (!$loginRes) {
      $this->error('账号不存在');
    } 

    //验证账号状态
    if ($loginRes['status'] != 0) {
      $this->error('账号已禁用');
    }
    if ($loginRes) {
      $token = Auth::makeToken();
      $userToken = new Token();
      $uid = $loginRes['user_id'];
      $userToken->setToken($token, $uid, $this->method);

      $this->success('登录成功', ['token' => $token, 'method' => $this->method, 'user_type' => $loginRes['user_type'], 'user_name' => $loginRes['user_name'], 'user_avatar' => $loginRes['avatar']]);
    } else {
      $this->error('登陆失败');
    }
  }

  // /**
  //  * 登录
  //  */
  public function userLogin()
  {
    $param = $this->request->param();
    //检查参数
    if (!isset($param['user_name']) || !isset($param['password'])) {
      $this->error('账号或密码不能为空');
    }

    //查账号是否存在
    $loginRes = Db::name('sys_user')->where(['user_name' => $param['user_name'], 'delete_time' => NULL])->find();
    if (!$loginRes) {
      $this->error('账号不存在');
    }
    //验证密码
    if (!password_verify($param['password'], $loginRes['password'])) {
      $this->error('密码错误');
    }
    //验证账号状态
    if ($loginRes['status'] != 0) {
      $this->error('账号已禁用');
    }
    if ($loginRes) {
      $token = Auth::makeToken();
      $userToken = new Token();
      $uid = $loginRes['user_id'];
      $userToken->setToken($token, $uid, $this->method);

      $this->success('登录成功', ['token' => $token, 'method' => $this->method, 'user_type' => $loginRes['user_type'], 'user_name' => $loginRes['user_name'], 'user_avatar' => $loginRes['avatar']]);
    } else {
      $this->error('登陆失败');
    }
  }
}
